package com.swq.java.code.chapter13.code27;

/**
 *  从程序运行来看并没有产生死锁，和书上描述流程不一致
 *  和code23一样，加入sleep，保证执行结果和书上逻辑一致
 */
public class Machine extends Thread {
    private int a;  //共享数据

    public void run() {
        for (int i = 0; i < 1000; i++) {
            synchronized (this) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                a += i;
                yield();  //给其他线程运行的机会
                a -= i;
                System.out.println("run method a = " + a);
            }
        }
    }

    public synchronized void reset() {
        a = 0;
        System.out.println("reset method a = " + a);
    }

    public static void main(String args[]) throws InterruptedException {
        Machine machine = new Machine();
        machine.start();
        yield();  //给machine线程运行的机会
        Thread.sleep(1000);
        machine.suspend();  //让machine线程暂停
        machine.reset();  //调用machine对象的同步代码块
        machine.resume();  //使machine线程恢复运行
    }
}